<?php
    require("./Utils.php");

    $post = getJsonParamter();

    $username = $post['username'];
    $id = "O_".time();
    $date = date("Y-m-d H:i:s");

    $conn = getConnection();
    mysqli_autocommit($conn,FALSE);
    $sql = "INSERT INTO `order` (id, user_id, status, date) VALUES(?, ?, 0, ?)";

    execute($conn, $sql, $id, $username, $date);

    $sql = "SELECT pet_id, number FROM cart WHERE user_id = ?";
    $shop_list = query_list($conn, $sql, $username);

    foreach($shop_list as $shop){
        $pet_id = $shop['pet_id'];
        $number = $shop['number'];
        
        $sql = "INSERT INTO pet_order(order_id, pet_id, pet_number) VALUES(?, ?, ?)";
        execute($conn, $sql, $id, $pet_id, $number);
    }

    $sql = "DELETE FROM cart WHERE user_id = ?";
    execute($conn, $sql, $username);

    mysqli_commit($conn);

    $data = array();

    $data['order_number'] = $id;

    getJson(200, '提交成功', $data);

    // else getJson(500, '提交失败', null);

?>